package com.bst.config;

import com.bst.base.domain.BaseDownload;
import com.bst.base.service.IBaseDownloadService;
import com.bst.common.utils.DateUtil;
import com.bst.common.utils.poi.ExcelUtil;
import com.bst.common.vo.ExcelExportVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.concurrent.LinkedBlockingQueue;

@Component
public class RunDownloadConfig implements ApplicationRunner {

    @Autowired
    IBaseDownloadService baseDownloadService;

    @Value("${ruoyi.download.active: false}")
    private Boolean isDownloadActive;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        // 获取并处理下载请求
        if(isDownloadActive) {
            Thread downloadThread = new Thread(() -> {
                processDownloadRequests();
            });
            downloadThread.start();
        }
    }

    // 处理下载请求
    public synchronized void processDownloadRequests() {
        LinkedBlockingQueue<ExcelExportVO> downloadQueue = DownloadManager.INSTANCE.getDownloadQueue();
        while (true) {
            System.out.println("执行时间："+ DateUtil.FORMAT_YYYY_MM_DD_HHMMSS.format(new Date()));
            if(downloadQueue.size()>0) {
                ExcelExportVO exportVO = null; // take方法是线程安全的
                try {
                    exportVO = downloadQueue.take();
                    // 模拟下载过程
                    String fileName = new ExcelUtil().createMoreSheetExcel(exportVO.getData(),exportVO.getSheetNames(),exportVO.getFileName());
                    BaseDownload download = new BaseDownload();
                    download.setNaFile(fileName);
                    download.setIdMenu(exportVO.getMenuId());
                    download.setNaMenu(exportVO.getMenuName());
                    download.setNaEmpCre(exportVO.getUserName());
                    download.setCdEmpCre(exportVO.getUserCode());
                    baseDownloadService.insertBaseDownload(download);
                } catch (InterruptedException e) {
                    System.out.println("EXCEL生成失败");
                    e.printStackTrace();
                }
            } else {
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
